/**
 * 
 */
package top.ewind.sender;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

import com.jfinal.kit.HttpKit;
import com.jfinal.weixin.sdk.utils.JsonUtils;

import top.ewind.model.SysDictory;
import top.ewind.util.DateUtil;


/**
 * @author wangchao
 *
 */
public class SmsSender implements Sender {


	public static String IPURL="https://api.ucpaas.com/2014-06-30/Accounts/ACCOUNTSID/Messages/templateSMS?sig=SIGNATURE";
	
	/**
	 * 发送短信
	 * @param accountSid 
	 * @param authToken
	 * @param appId
	 * @param templateId
	 * @param to 手机号码
	 * @param param 发送内容
	 * @return String
	 * @throws UnsupportedEncodingException 
	 */
	public static String templateSMS(String accountSid, String authToken,
		String appId, String templateId, String to, String param){
		String reqStr = "";
		try{					
			String timestamp = DateUtil.dateToStr(DateUtil.yyyyMMddHHmmss,new Date());
			String signature = DigestUtils.md5Hex(accountSid + authToken + timestamp);
			String url = IPURL.replace("ACCOUNTSID", accountSid).replace("SIGNATURE",signature.toUpperCase());
			Map<String,String> headers = new HashMap<String,String>();
			headers.put("Accept", "application/json");
			headers.put("Content-Type", "application/json;charset=utf-8");
			String src = accountSid + ":" + timestamp;			
			String auth = Base64.encodeBase64String(src.getBytes("UTF-8"));
			headers.put("Authorization", auth);
			Map<String,String> tplsms = new HashMap<String,String>();
			tplsms.put("appId", appId);
			tplsms.put("templateId", templateId);
			tplsms.put("to", to);
			tplsms.put("param", param);
			String body="{\"templateSMS\":"+JsonUtils.toJson(tplsms)+"}";
			reqStr = HttpKit.post(url, body, headers);		
		}catch(Exception e){}
		return reqStr;
	}
	
	
	public void send(String username, String content) {
		templateSMS(SysDictory.getConfig("smsAccountSid"), SysDictory.getConfig("smsAuthToken"), 
				SysDictory.getConfig("smsAppId"), SysDictory.getConfig("smsTemplateId"), username, content);
	}

}
